package com.ddc.study.feature.query;

import com.ddc.study.entity.Article;
import com.ddc.study.entity.History;
import com.ddc.study.entity.HotKey;
import com.ddc.study.entity.MainData;
import com.ddc.study.util.Log;

import java.util.List;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;

/**
 * Created on 2018/4/28.
 *
 * @author lshun
 * @version 1.0
 */
class QueryPresenter extends QueryContract.IPresenter {
    private final QueryContract.IModel mModel = new QueryModel();

    @Override
    void loadHotKey() {
        Runnable runnable = () -> {
            final List<HotKey> data = mModel.loadHotKey();

            if (!isViewAttached()) return;
            getView().runOnUIThread(() -> {
                if (isViewAttached()) {
                    getView().showHotKeyData(data);
                }
            });
        };

        mThreadPool.submit(runnable);
    }

    @Override
    void loadHistory() {
        Runnable runnable = () -> {
            final List<History> historyList = mModel.loadHistory();

            if (!isViewAttached()) return;
            getView().runOnUIThread(() -> {
                if (isViewAttached()) {
                    getView().showHistoryData(historyList);
                }
            });
        };

        mThreadPool.submit(runnable);
    }

    @Override
    void queryWord(@IntRange(from = 0) final int page, final String word) {
        Log.e("QueryPresenter", "page = " + page + ", word = " + word);
        if (page < 0) return;

        Runnable runnable = () -> {
            //仅在首次搜索时处理以及刷新历史记录
            if (page == 0) {
                //TODO 返回值未使用
                mModel.handleKeywordToHistory(word);
                //处理完后刷新历史记录
                loadHistory();
            }
            final MainData<Article> queryData = mModel.queryWord(page, word);

            if (!isViewAttached()) return;
            getView().runOnUIThread(() -> {
                if (isViewAttached()) {
                    getView().showQueryData(queryData);
                }
            });
        };

        mThreadPool.submit(runnable);
    }

    @Override
    void deleteWord(@NonNull final String word) {
        Runnable runnable = () -> {
            final boolean success = mModel.deleteWord(word);

            if (!isViewAttached()) return;
            getView().runOnUIThread(() -> {
                if (isViewAttached()) {
                    getView().showDeleteWordResult(success);
                }
            });
        };

        mThreadPool.submit(runnable);
    }

    @Override
    void deleteAllWords() {
        Runnable runnable = () -> {
            final boolean success = mModel.deleteAllWords();

            if (!isViewAttached()) return;
            getView().runOnUIThread(() -> {
                if (isViewAttached()) {
                    getView().showDeleteAllWordsResult(success);
                }
            });
        };

        mThreadPool.submit(runnable);
    }
}
